import React, { Component } from 'react';
import ReactDom from 'react-dom';
import axios from 'axios';
import util from "@/common/util"
import layer from '@/common/layer'
import ImgView from '@/components/imgview'

class Reg extends Component {
    constructor(props) {
        super(props);
        this.state = {
            username: '',
            username_valid: true,
            password: '',
            password_valid: true,
            code: '',
            code_valid: true,
            xieyi: true,
            xieyi_valid: true,
            userType: 1,
            canreg: true,
            second: 0,
            imgShow:false,
            qrcodeUrl:"http://img0.rongsue.com/wechat/qrcode.jpg"
        }
        this.valids = [
            {
                key: 'username',
                func(str) {
                    if (str.length !== 11) {
                        layer.open({
                            content: "请输入正确的手机号码",
                            btn: '好的'
                        })
                        return false
                    }
                    return true
                }
            },
            {
                key: 'password',
                func(str) {
                    if (str.length === 0) {
                        layer.open({
                            content: "请输入密码",
                            btn: '好的'
                        })
                        return false
                    }
                    if (str.length < 6 || str.length > 16) {
                        layer.open({
                            content: "密码长度需要大于6个字符且小于16个字符",
                            btn: '好的'
                        })
                        return false
                    }
                    if (!str.match(/^[A-Za-z0-9\\\\u4e00-\\u9fa5]+$/gi)){
                        layer.open({
                            content: "密码中不能包含特殊字符",
                            btn: '好的'
                        })
                        return false
                    }
                    return true
                }
            },
            {
                key: 'code',
                func(str) {
                    if (str.length === 0) {
                        layer.open({
                            content: "请输入验证码",
                            btn: '好的'
                        })
                        return false
                    }
                    return true
                }
            },
            {
                key: 'xieyi',
                func(bol) {
                    if (!bol) {
                        layer.open({
                            content: "请同意注册协议",
                            btn: '好的'
                        })
                        return false
                    }
                    return true
                }
            }
        ]
    }

    usernameChange(e) {
        this.setState({
            username: e.target.value
        });
    }

    passwordChange(e) {
        this.setState({
            password: e.target.value
        });
    }

    codeChange(e) {
        this.setState({
            code: e.target.value
        });
    }

    async beforeSendCode() {
        if (this.state.second !== 0) { return }

        if (this.state.username.length === 0) {
            this.setState({
                username_valid: false
            })
            return;
        } else {
            this.setState({
                username_valid: true
            })
        }

        let phone = this.state.username
        let res = await axios.post(`${util.host}/auth/checkValidPhone/${phone}`)

        if (res.data.success) {
            this.setState({
                second: 60
            });
            let timer = setInterval(() => {
                if (this.state.second < 1) {
                    clearInterval(timer)
                } else {
                    this.setState({
                        second: this.state.second - 1
                    })
                }
            }, 1000)
            this.sendCode()

        } else {
            layer.open({
                content: "该手机号码已被注册",
                btn: "好的"
            })
            return;
        }
    }

    async sendCode() {
        let phone = this.state.username
        let res = await axios.get(`${util.host}/auth/code/sms`, {
            params: {
                deviceId: phone,
                phone: phone
            }
        })
        layer.open({
            content: "验证码已发送",
            btn: "好的"
        })
    }

    async regUser() {

        for (let item of this.valids) {
            if (!item.func(this.state[item.key])) {
                this.setState({
                    [item.key + '_valid']: false
                })
                return;
            } else {
                this.setState({
                    [item.key + '_valid']: true
                })
            }
        }

        let sendobj = {
            phone: this.state.username,
            smsCode: this.state.code,
            deviceId: this.state.username,
            loginPwd: this.state.password,
            confirmPwd: this.state.password,
            registerSource: 1,
            userType: this.state.userType
        }

        let res = await axios.post(`${util.host}/auth/register${util.obj2query(sendobj)}`).catch((e, data) => {
            if (e.response.data.message)
            {
                layer.open({
                    content: e.response.data.message,
                    btn: "好的"
                })
            }
        })

        if (!res){
            return;
        }

        if (this.state.userType===1)
        {
            layer.open({
                content: "注册成功，即将转入登录页面",
                btn: "去登录",
                yes:function () {
                    window.location.href = "./login.html"
                }
            })
        }else{
            layer.open({
                content: "注册成功，可登录rongsue.com或可至公众号帮助中心",
                btn: "确定"
            })
        }
    }

    componentDidMount() {
        /*
        console.log(util.getQuery().code)
        if (util.getQuery().code){
            console.log(util.getQuery().code)
        }
        else{
            window.location.href=`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${util.appid}&redirect_uri=${encodeURIComponent(window.location.href)}&response_type=code&scope=snsapi_base&state=#wechat_redirect`
        }*/
        console.log(util.getQuery())
        if (util.getQuery().usertype)
        {
            this.setState({
                userType:parseInt(util.getQuery().usertype)
            })
        }
    }

    render() {
        return (
            <div>
                <div className="view">
                    <div className="typetab">
                        <a href="javascript:;" className={this.state.userType === 2 ? 'active' : ''} onClick={() => { this.setState({ userType: 2 }) }}>渠道注册</a>
                        <a href="javascript:;" className={this.state.userType === 1 ? 'active' : ''} onClick={() => { this.setState({ userType: 1 }) }}>用户注册</a>
                        <div className="bb" style={{ left: (this.state.userType === 2) ? "0%" : "50%" }}></div>
                    </div>
                    <div id="reg">
                        <input type="text" className="text" placeholder="请输入手机号" style={{ borderColor: (this.state.username_valid) ? '#E6E6E6' : '#FF0000' }} value={this.state.username} onChange={this.usernameChange.bind(this)} maxLength="11"/>

                        <div style={{ position: "relative" }}>
                            <input type="text" className="text" placeholder="请输入验证码" style={{ borderColor: (this.state.code_valid) ? '#E6E6E6' : '#FF0000' }} value={this.state.code} onChange={this.codeChange.bind(this)} />
                            <input type="button" className="yzbtn" value={(this.state.second === 0) ? '获取验证码' : `剩余${this.state.second}秒`} onClick={this.beforeSendCode.bind(this)} />
                        </div>
                        <div className="cb"></div>
                        <input type="text" className="text" placeholder="请输入密码" style={{ borderColor: (this.state.password_valid) ? '#E6E6E6' : '#FF0000' }} value={this.state.password} onChange={this.passwordChange.bind(this)} />
                        <div className="mt20">
                            <span className="dot" onClick={() => { this.setState({ xieyi: !this.state.xieyi }) }}>
                                {(this.state.xieyi) ? <i></i> : null}
                            </span>
                            <span className="xieyilink">
                                <span>我已经阅读并同意</span>
                                <a href="/contract/ptfwtk.html" target="_blank">《平台注册服务协议》</a>
                            </span>
                        </div>
                        <input type="button" className="btn" value="注册" onClick={this.regUser.bind(this)} />
                        <div className="linkbox">
                            <a href="./login.html" className="fr">已有账号，<span>登录&gt;&gt;</span></a>
                            <a href="javascript:;" style={{ display: "none" }}>忘记密码?</a>
                        </div>
                        <div className="cb"></div>
                        <div style={{ height: "20px" }}></div>
                        <div>
                            <img src={this.state.qrcodeUrl} style={{width:"150px"}} alt="" />
                        </div>
                        
                    </div>
                </div>
                <ImgView show={this.state.imgShow} src={this.state.qrcodeUrl} onClick={()=>{this.setState({imgShow:false})}}/>
            </div>
        )
    }
}


ReactDom.render(< Reg />, document.getElementById('app'))